package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn;
import com.ruoyi.generator.service.GenTableColumnServiceImpl;
import com.ruoyi.generator.service.GenTableServiceImpl;
import com.ruoyi.generator.service.IGenTableColumnService;
import lombok.extern.slf4j.Slf4j;
import org.anyline.controller.impl.AnylineController;
import org.anyline.entity.DataRow;
import org.anyline.entity.DataSet;
import org.anyline.entity.DefaultPageNavi;
import org.anyline.entity.PageNavi;
import org.anyline.service.AnylineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/system/dynamic")
public class DynamicFormController extends BaseController {
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";
    @Autowired
    @Qualifier("anyline.service")
    protected AnylineService service;
    @Autowired
    JdbcTemplate jdbcTemplate;
    public AjaxResult get(){
        return AjaxResult.success();
    }
    @Resource
    private GenTableServiceImpl tableService;
    @Resource
    private GenTableColumnServiceImpl columnService;
    @Resource
    private HttpServletRequest request;

    @Autowired
    private IGenTableColumnService genTableColumnService;

    @PostMapping("getDataList")
    public TableDataInfo getList(@RequestBody JSONObject queryJson){
        Integer pageNum = Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1);
        Integer pageSize =  Convert.toInt(ServletUtils.getParameter(PAGE_SIZE));
        PageNavi page = new DefaultPageNavi(pageNum, pageSize);
        Integer tableId = queryJson.getInteger("tableId");
        GenTable table =   tableService.getById(tableId);
        DataSet dataSet = service.querys(table.getTableName(),page,queryJson.getJSONObject("searchForm"),"is_delete=0");


        LambdaQueryWrapper<GenTableColumn> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GenTableColumn::getTableId,tableId);
        List<GenTableColumn> columnList = columnService.list(lambdaQueryWrapper);
        List<JSONObject> list =new ArrayList<>();
        dataSet.getRows().forEach(it->{
            JSONObject itRow =new JSONObject();
            columnList.forEach(ix->{
                String javaField = ix.getJavaField();
                String columnName = ix.getColumnName();
                Object v = it.get(columnName.toUpperCase());
                itRow.put(javaField,v);
            });
            list.add(itRow);
        });

      //long total=  dataSet.total();
      //long size = dataSet.size();
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(dataSet.getNavi().getTotalRow());
        return rspData;


    }
    @GetMapping("/getDisplayColumnList/{tableId}")
    public AjaxResult getDisplayColumnList(@PathVariable Integer tableId){
        LambdaQueryWrapper<GenTableColumn> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GenTableColumn::getTableId,tableId).eq(GenTableColumn::getShowInList,1).orderByAsc(GenTableColumn::getListColumnSort);
        List<GenTableColumn> list = genTableColumnService.list(lambdaQueryWrapper);
       return AjaxResult.success(list);
    }

    /**
     * 获取一条数据
     * @param tableId
     * @param id
     * @return
     */
    @GetMapping("getDataDetail")
    public AjaxResult getDataDetail(Integer tableId, Integer id){
        GenTable table =   tableService.getById(tableId);
        DataRow dataRow = service.query(table.getTableName(),"id ="+id.toString());
        JSONObject formData = new JSONObject();
        LambdaQueryWrapper<GenTableColumn> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GenTableColumn::getTableId,tableId);
        List<GenTableColumn> columnList = columnService.list(lambdaQueryWrapper);
        columnList.forEach(it->{
            String javaField = it.getJavaField();
            String columnName = it.getColumnName();
            Object v = dataRow.get(columnName);
            formData.put(javaField,v);
        });
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("formData",formData);
        return AjaxResult.success(jsonObject);

    }




    /**
     * 新增一条
     * @param dataObj
     * @return
     */
    @PostMapping("add")
    public AjaxResult add(@RequestBody JSONObject dataObj){
        Integer tableId = dataObj.getInteger("tableId");
        Integer did = dataObj.getInteger("id");
        JSONObject formData = dataObj.getJSONObject("formData");
        GenTable table =   tableService.getById(tableId);
        LambdaQueryWrapper<GenTableColumn> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GenTableColumn::getTableId,tableId);
        List<GenTableColumn> columnList = columnService.list(lambdaQueryWrapper);
        //插入数据
        DataRow row = new DataRow();

        columnList.forEach(it->{
           String javaField = it.getJavaField();
            String columnName = it.getColumnName();
          Object v = formData.get(javaField);
          row.put(columnName,v);
        });
        row.put("create_time",DateUtils.dateTime());
        row.put("create_user_id", SecurityUtils.getUserId());
        row.put("create_user_name", SecurityUtils.getLoginUser().getUser().getNickName());
        service.insert(table.getTableName(), row);
        return AjaxResult.success();
    }

    /**
     * 更新
     * @param dataObj
     * @return
     */
    @PutMapping("update")
    public AjaxResult update(@RequestBody JSONObject dataObj){
        Integer tableId = dataObj.getInteger("tableId");
        Integer did = dataObj.getInteger("id");
        JSONObject formData = dataObj.getJSONObject("formData");
        GenTable table =   tableService.getById(tableId);
        LambdaQueryWrapper<GenTableColumn> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GenTableColumn::getTableId,tableId);
        List<GenTableColumn> columnList = columnService.list(lambdaQueryWrapper);
        //插入数据
        DataRow row = new DataRow();

        columnList.forEach(it->{
            String javaField = it.getJavaField();
            String columnName = it.getColumnName();
            Object v = formData.get(javaField);
            row.put(columnName,v);
        });
        row.put("id",did);
        row.put("update_time",DateUtils.dateTime());
        row.put("update_user_id", SecurityUtils.getUserId());
        row.put("update_user_name", SecurityUtils.getLoginUser().getUser().getNickName());
        service.update(table.getTableName(), row);
        return AjaxResult.success();
    }
    @DeleteMapping("/delete/{tableId}/{idList}")
    public AjaxResult delete(@PathVariable Integer tableId,@PathVariable List<Integer> idList){
        GenTable table =   tableService.getById(tableId);

        service.execute("update "+table.getTableName()+" set is_delete=1 where id  in ( "+idList.stream().map(it->it.toString()).collect(Collectors.joining(","))+" )");
        return AjaxResult.success(true);

    }
}
